<template>
  <div v-loading="allLoading" class="list-table noPad">
    <el-tabs v-model="activeName" @tab-click="clickMenu">
      <el-tab-pane v-for="(item, key) in childMenuTabs" :key="key" :lazy="true" :label="$t(item.menuName)" :name="item.menuName">
        <component :is="menuPath" v-if="item.flag" ref="menuPath" />
      </el-tab-pane>
      <el-tab-pane :label="$t('数据上传')" name="pcwDataMainList" />
      <el-tab-pane :label="$t('财务分析')" name="pcwAnalyze" />
      <el-tab-pane :label="$t('关键指标')" name="pcwReport" />
      <el-tab-pane :label="$t('指标监控')" name="riskMonitor" />
      <template v-if="easyddEnable">
        <el-tab-pane :label="$t('横向对比')" name="easyDDHorizontal" />
        <el-tab-pane :label="$t('智能分析')" name="easyDDAlgorithmic" />
      </template>
      <el-tab-pane :label="$t('公司财务模版')" name="pcwCmyTempTabs" />
      <template v-if="easyddEnable">
        <el-tab-pane :label="$t('横向对比')" name="easyDDHorizontal" />
        <el-tab-pane :label="$t('智能分析')" name="easyDDAlgorithmic" />
      </template>

    </el-tabs>

    <!-- <el-tabs v-model="view" @tab-click="handleClick">
      <el-tab-pane :label="$t('财务数据')" name="pcwDataBaseList" />
      <el-tab-pane :label="$t('科目数据')" name="pcwSubjectDataList" />
      <el-tab-pane :label="$t('数据上传')" name="pcwDataMainList" />
      <el-tab-pane :label="$t('财务分析')" name="pcwAnalyze" />
      <el-tab-pane :label="$t('关键指标')" name="pcwReport" />
      <el-tab-pane :label="$t('指标监控')" name="riskMonitor" />
      <el-tab-pane :label="$t('公司财务模版')" name="pcwCmyTempTabs" />
    </el-tabs> -->

    <!-- <div v-if="view==='pcwDataBaseList' && hidden">
      <pcwDataBaseList :company-id="companyId" />
    </div>
    <div v-if="view==='pcwSubjectDataList' && hidden">
      <pcwSubjectDataList :company-id="companyId" />
    </div> -->
    <div v-if="activeName==='easyDDHorizontal' && easyddflag ">
      <pcwEasyDD :preview-url="previewUrl" />
    </div>
    <div v-if="activeName==='easyDDAlgorithmic' && easyddflag ">
      <pcwEasyDD :preview-url="previewUrl" />
    </div>
    <div v-if="activeName==='pcwDataMainList' && hidden">
      <pcwDataMainList :company-id="companyId" />
    </div>
    <div v-if="activeName==='pcwReport' && hidden">
      <pcwReport :company-id="companyId" />
    </div>
    <div v-if="activeName==='pcwAnalyze' && hidden">
      <pcwAnalyze :company-id="companyId" />
    </div>
    <div v-if="activeName==='riskMonitor' && hidden">
      <pcwRiskMonitorList :company-id="companyId" :deal-id="undefined" />
    </div>
    <div v-if="activeName==='pcwCmyTempTabs' && hidden">
      <pcwCmyTempTabs ref="pcwCmyTempTabs" :company-id="companyId" @updateTemplate="updateTemplate" />
    </div>

    <el-dialog :title="$t('选择模板')" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="showTemp" width="50%" append-to-body @close="handleClose">
      <el-form ref="form" :model="form">
        <el-col :span="24">
          <el-form-item :label="$t('选择模板')">
            <el-tooltip placement="top">
              <div slot="content" v-text="validateMsg" />
              <i class="el-icon-question" />
            </el-tooltip>
            <el-select v-model="form.typeId" :placeholder="$t('选择模板')">
              <el-option
                v-for="dict in sysPcwTypeOptions"
                :key="dict.id"
                :label="$t(dict.name)"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTemp = false">{{ $t("取消") }}</el-button>
        <el-button type="primary" @click="asyncCmyTemp">{{ $t("确定") }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { easyDDUrl } from '@/api/company/pcw/pcwDataMain'
import { getConfigKey } from '@/api/system/config'
import pcwDataMainList from './pcwDataMainList.vue'
// import pcwSubjectDataList from './pcwSubjectDataList.vue'
import pcwReport from './pcwReport.vue'
// import pcwDataBaseList from './pcwDataBaseList.vue'
import pcwAnalyze from './pcwAnalyze.vue'
import pcwRiskMonitorList from './pcwRiskMonitorList.vue'
import pcwCmyTempTabs from './pcwCmyTempTabs.vue'
import pcwEasyDD from './pcwEasyDD.vue'
import {
  childMenuList
} from '@/api/system/menu'
import {
  getAsyncComponent
} from '@/utils'
import {
  getByCompanyId,
  asyncCmyTemp,
  getCurrentCompanyTemp
} from '@/api/company/pcw/pcwCmyInit'
import {
  dealListPcwSysType
} from '@/api/company/pcw/pcwSysType'
import {
  refreshIndicator
} from '@/api/company/pcw/pcwDataKeys'
export default {
  components: {
    pcwDataMainList,
    // pcwSubjectDataList,
    pcwReport,
    // pcwDataBaseList,
    pcwAnalyze,
    pcwRiskMonitorList,
    pcwCmyTempTabs,
    pcwEasyDD
  },
  data() {
    return {
      easyddEnable: false,
      easyddflag: false,
      previewUrl: '',
      activeName: '财务数据',
      menuIdent: 'pcw_tabs',
        // 子页签
      childMenuTabs: [],
      // 遮罩层
      loading: true,
      // 展示视图
      view: 'pcwDataBaseList',
      companyId: this.$route.query.companyId || this.$route.query.id,
      // 查询参数
      queryParams: {
        // 公司ID
        companyId: this.$route.query.companyId || this.$route.query.id
      },
      form: {
        // 选择的财报类型
        typeId: undefined,
        companyId: undefined
      },
      // 是否显示选择模板遮罩层
      showTemp: false,
      // 说明文字
      validateMsg: '请选择财务数据模板，选择后系统将初始化当前公司的财务数据科目和关键指标！',
      // 财报类型option
      sysPcwTypeOptions: [],
      allLoading: false,
      hidden: true

    }
  },
  created() {
    this.initSysTypeOption()
    this.checkCompanyTemp()
    getConfigKey('easyDD_analyse').then(res => {
        this.easyddEnable = (res.msg === 'true')
      })
  },
  mounted() {
    // if (this.$route.path.indexOf('fundBasehome') !== -1 || this.$route.path.indexOf('fundBaseSpvHome') !== -1) {
    //   this.companyId = this.$route.query.id
    // } else {
    //   this.companyId = this.$route.query.companyId
    // }
    this.queryParams.companyId = this.$route.query.companyId || this.$route.query.id
    this.form.companyId = this.$route.query.companyId || this.$route.query.id
    this.listLoad()
  },
  methods: {
    listLoad() {
        this.loading = true
        // 菜单列表
        childMenuList(this.menuIdent).then(response => {
          this.childMenuTabs = response.rows
          if (this.childMenuTabs !== null && this.childMenuTabs !== undefined && this.childMenuTabs.length > 1) {
            this.activeName = this.childMenuTabs[0] === undefined ? '' : this.childMenuTabs[0].menuName
            this.clickMenu(response.rows[0])
          } else if (this.childMenuTabs !== null && this.childMenuTabs !== undefined && this.childMenuTabs.length > 0) {
            this.activeName = this.childMenuTabs[0] === undefined ? '' : this.childMenuTabs[0].menuName
            this.clickMenu(response.rows[0])
            // this.$router.push({ path: '@/view/error/404' })
          }
          this.loading = false
        })
      },
      clickMenu(tab) {
        this.childMenuTabs && this.childMenuTabs.forEach(item => {
          if (item.menuName === tab.menuName || item.menuName === tab.name) {
            this.$nextTick(() => {
              this.$set(item, 'flag', true)
              this.importFormPath(item.component)
            })
          } else {
            this.$set(item, 'flag', false)
          }
        })
        if (tab.name === 'easyDDHorizontal' || tab.name === 'easyDDAlgorithmic') {
             easyDDUrl(tab.name, this.companyId).then(res => {
              this.previewUrl = res.msg
              this.easyddflag = true
            })
        }
      },
      // 引入组件
      importFormPath(menuPath) {
        this.panelType = undefined
        if (menuPath) {
          if (menuPath.indexOf('?') === -1) { // 不含问号
            this.menuPath = getAsyncComponent('@/views/' + menuPath)
            this.parameter = {}
          } else {
            const index = menuPath.lastIndexOf('?')
            const sMenuPath = menuPath.substring(0, index)
            this.menuPath = getAsyncComponent('@/views/' + sMenuPath)

            // 增加参数
            const newKey = menuPath.split('?')[1]
            var newstr = newKey.replace(/=/g, '":"')
            const objectKey = '{"' + newstr.replace(/&/g, '","') + '"}'
            this.parameter = JSON.parse(objectKey)
            if (this.parameter !== undefined && this.parameter.contractType !== undefined) {
              this.panelType = this.parameter.contractType
            }
          // 财务预算利润/现金/分配 报表类型查询条件
            if (this.parameter.subjectType !== undefined) {
              this.$route.params.subjectType = this.parameter.subjectType
            }
          }
          // 地址栏添加左侧菜单地址
          this.$nextTick(() => {
            this.$route.params.panelType = this.panelType
          })
        } else {
          const error = 'error/404'
          this.importFormPath(error)
        }
      },

    handleClick(tab, event) {
      console.log(tab, event)
    },
    // 第一次点击财务数据，需要先将系统模板中的科目和关键指标初始化到当前公司模板中
    checkCompanyTemp() {
      this.loading = true
      getByCompanyId(this.queryParams).then(res => {
        if (res.data === null) {
          this.showTemp = true
          this.validateMsg = this.$t('请选择财务数据模板，选择后系统将初始化当前公司的财务数据科目和关键指标！')
        }
        this.loading = false
      })
    },
    // 获取系统所有的财务报表模板分类
    initSysTypeOption() {
      dealListPcwSysType(this.queryParams).then(res => {
        this.sysPcwTypeOptions = res.rows
      })
    },
    // 同步当前公司的财务模板
    asyncCmyTemp() {
      if (!this.form.typeId || this.form.typeId === '') {
        this.msgError(this.$t('请选择财务分类模板!'))
      } else {
        this.showTemp = false
        this.allLoading = true
        asyncCmyTemp(this.form).then(res => {
          if (res.code === 200) {
            this.msgSuccess(this.$t('初始化成功'))
            this.allLoading = false
            this.showTemp = false
            this.view = 'pcwCmyTempTabs'
          }
          // 更新表格
          this.$refs.pcwCmyTempTabs.$refs.pcwTempKeyList.getList()
          //  更换模板后立即触发关键指标重新计算
          refreshIndicator(this.$route.query.companyId).then(() => {}).catch(() => {
            this.msgError(this.$t('重新计算失败!'))
          })
        })
      }
    },
    updateTemplate() {
      this.showTemp = true
      // 查询当前公司用的财务模板
      this.$nextTick(() => {
        getCurrentCompanyTemp(this.companyId).then(response => {
          if (response.code === 200) {
            this.form.typeId = response.data.typeId
          }
        })
      })
    },
    handleClose() {
      getByCompanyId(this.queryParams).then(res => {
        if (!this.form.typeId && res.data === null) {
          this.hidden = false
        }
      })
    }
  }
}
</script>
